package com.tiger.web.controller.project;

import com.tiger.common.annotation.Log;
import com.tiger.common.core.controller.BaseController;
import com.tiger.common.core.domain.AjaxMapResult;
import com.tiger.common.core.domain.AjaxResult;
import com.tiger.common.core.domain.entity.SysDept;
import com.tiger.common.core.domain.entity.SysUser;
import com.tiger.common.core.domain.model.LoginUser;
import com.tiger.common.core.page.TableDataInfo;
import com.tiger.common.enums.BusinessType;
import com.tiger.common.utils.SecurityUtils;
import com.tiger.common.utils.ServletUtils;
import com.tiger.common.utils.spring.SpringUtils;
import com.tiger.communal.domain.CommonAgency;
import com.tiger.communal.mapper.CommonAgencyMapper;
import com.tiger.framework.web.service.TokenService;
import com.tiger.project.domain.Contract;
import com.tiger.project.domain.ContractBill;
import com.tiger.project.domain.ContractSponsor;
import com.tiger.project.domain.req.PartyInfo;
import com.tiger.project.mapper.ContractBillMapper;
import com.tiger.project.service.IContractBillService;
import com.tiger.project.service.IContractSponsorService;
import com.tiger.system.mapper.SysDeptMapper;
import com.tiger.web.controller.communal.CommonAgencyController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import io.swagger.annotations.ApiParam;
import org.apache.ibatis.annotations.Param;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;


/**
 * 【合同发起】Controller
 *
 * @author standard
 * @date 2022-09-22
 */
@Api(tags = "合同发起")
@RestController
@RequestMapping("/system/sponsor")
public class ContractSponsorController extends BaseController {
    @Autowired
    private IContractSponsorService contractSponsorService;
    @Resource
    private SysDeptMapper deptMapper;
    @Autowired
    private CommonAgencyMapper agencyMapper;

    /**
     * 查询【合同发起】列表
     */
    @ApiOperation(value = "查询【合同发起】列表")
    //@PreAuthorize("@ss.hasPermi('system:sponsor:list')")
    @GetMapping("/list")
    public TableDataInfo list(ContractSponsor contractSponsor) {
        LoginUser loginUser = SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest());
        contractSponsor.setCompanyId(loginUser.getUser().getDeptId());
        startPage();
        List<ContractSponsor> list = contractSponsorService.selectContractSponsorList(contractSponsor);
        return getDataTable(list);
    }

    /**
     * 查询【合同台账】列表
     */
    @ApiOperation(value = "查询【合同台账】列表")
    //@PreAuthorize("@ss.hasPermi('system:sponsor:list')")
    @GetMapping("/pigeonholeList")
    public TableDataInfo pigeonholeList(ContractSponsor contractSponsor) {
        LoginUser loginUser = SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest());
        contractSponsor.setCompanyId(loginUser.getUser().getDeptId());
        startPage();
        List<ContractSponsor> list = contractSponsorService.selectContractSponsorPigeonholeList(contractSponsor);
        return getDataTable(list);
    }


    /**
     * 查询【合同预警】列表
     */
    @ApiOperation(value = "查询【合同预警】列表")
    //@PreAuthorize("@ss.hasPermi('system:sponsor:list')")
    @GetMapping("/warning")
    public TableDataInfo warning(ContractSponsor contractSponsor) {
        LoginUser loginUser = SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest());
        contractSponsor.setCompanyId(loginUser.getUser().getDeptId());
        startPage();
        List<ContractSponsor> list = contractSponsorService.selectContractSponsorWarningList(contractSponsor);
        return getDataTable(list);
    }




    /**
     * 新增【合同发起】
     */
    @ApiOperation(value = "新增【合同发起】")
    //@PreAuthorize("@ss.hasPermi('system:sponsor:add')")
//    @Log(title = "新增【合同发起】", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@RequestBody ContractSponsor contractSponsor) throws ParseException {
        LoginUser loginUser = SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest());
        contractSponsor.setCompanyId(loginUser.getUser().getDeptId());
        return toAjax(contractSponsorService.insertContractSponsor(contractSponsor,loginUser));
    }

    /**
     * 修改【合同发起】
     */
    @ApiOperation(value = "修改【合同发起】")
    //@PreAuthorize("@ss.hasPermi('system:sponsor:edit')")
//    @Log(title = "修改【合同发起】", businessType = BusinessType.UPDATE)
    @PutMapping("/edit")
    public AjaxResult edit(@RequestBody ContractSponsor contractSponsor) throws ParseException {
        return toAjax(contractSponsorService.updateContractSponsor(contractSponsor));
    }



    @ApiOperation(value = "合同预警数量")
    @GetMapping(value = "/warningCount")
    public AjaxMapResult warningCount(@ApiParam(value = "1-房屋  2-土地 ")String letWay){
        LoginUser loginUser = SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest());
        Long deptId = loginUser.getUser().getDeptId();
        return AjaxMapResult.success(contractSponsorService.warningCount(letWay,deptId));
    }

    @ApiOperation(value = "生成账单")
    @GetMapping(value = "/bill")
    public TableDataInfo bill(@ApiParam(value = "合同开始时间") Date rentStateTime,@ApiParam(value = "合同结束时间") Date rentEndTime,
                              @ApiParam(value = "付款周期") String paymentCycle,@ApiParam(value = "年租金") BigDecimal yearlyRent,
                              @ApiParam(value = "合同id") Long contractSponsorId,Boolean isAlter) throws ParseException {
        startPage();
        List<ContractBill> billList = contractSponsorService.billCopy(rentStateTime, rentEndTime, paymentCycle, yearlyRent, contractSponsorId,isAlter);
        return getDataTable(billList);
    }

    @ApiOperation(value = "合同发起审核回调")
    //@PreAuthorize("@ss.hasPermi('system:contract:edit')")
//    @Log(title = "【合同发起审核回调】", businessType = BusinessType.UPDATE)
    @GetMapping("/callBack")
    public AjaxResult callBack(@ApiParam(value = "合同发起id") Long id,
                               @ApiParam(value = "审核状态 3-审批通过，4-已驳回") Long status,String oaFile) {
        return toAjax(contractSponsorService.callBack(id,status,oaFile));
    }

    /**
     * 获取甲方  登录者所在公司+下级公司+代营公司
     */
    @ApiOperation(value = "获取甲方")
    @GetMapping("/getParty")
    public List<PartyInfo> getParty(){
        PartyInfo partyInfo = null;
        List<PartyInfo> partyInfoList = new ArrayList<>();
        SysUser user = SecurityUtils.getLoginUser().getUser();

        PartyInfo partyInfo1 = new PartyInfo();
        partyInfo1.setSource(0);
        partyInfo1.setId(user.getDeptId());
        partyInfo1.setName(user.getDept().getDeptName());
        partyInfoList.add(partyInfo1);
        //子公司1
        SysDept sysDept = new SysDept();
        sysDept.setParentId(user.getDeptId());
        List<SysDept> deptList = deptMapper.selectDeptList(sysDept);
        for (SysDept s : deptList){
            partyInfo = new PartyInfo();
            partyInfo.setId(s.getDeptId());
            partyInfo.setSource(0);
            partyInfo.setName(s.getDeptName());
            partyInfoList.add(partyInfo);
        }
        //代营公司
        CommonAgency agency = new CommonAgency();
        agency.setCompanyId(user.getDeptId());
        List<CommonAgency> agencyList = agencyMapper.selectCommonAgencyList(agency);
        for (CommonAgency c : agencyList){
            partyInfo = new PartyInfo();
            partyInfo.setName(c.getOrganShortName());
            partyInfo.setId(c.getId());
            partyInfo.setSource(1);
            partyInfoList.add(partyInfo);
        }
        return partyInfoList;
    }

    /**
     * 总计租率
     */
    @ApiOperation(value = "总计租率")
    @PostMapping("/getTotalRentalRate")
    public AjaxResult getTotalRentalRate() {
        LoginUser loginUser = SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest());
        return AjaxResult.success(contractSponsorService.getTotalRentalRate(loginUser.getUser().getDeptId()));
    }

    /**
     * 总出租率
     */
    @ApiOperation(value = "总出租率")
    @PostMapping("/getTotalLettingRate")
    public AjaxResult getTotalLettingRate() {
        LoginUser loginUser = SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest());
        return AjaxResult.success(contractSponsorService.getTotalLettingRate(loginUser.getUser().getDeptId()));
    }

    /**
     * 总计租均价
     */
    @ApiOperation(value = "总计租均价")
    @PostMapping("/getAverageRentalPrice")
    public AjaxResult getAverageRentalPrice() {
        LoginUser loginUser = SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest());
        return AjaxResult.success(contractSponsorService.getAverageRentalPrice(loginUser.getUser().getDeptId()));
    }

    /**
     * 总平效
     */
    @ApiOperation(value = "总平效")
    @PostMapping("/getTotalUtilityEquality")
    public AjaxResult getTotalUtilityEquality() {
        LoginUser loginUser = SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest());
        return AjaxResult.success(contractSponsorService.getTotalUtilityEquality(loginUser.getUser().getDeptId()));
    }

    /**
     * 账面平效排行榜
     */
    @ApiOperation(value = "账面平效排行榜")
    @PostMapping("/getBookValueUtilityEqualityRanking")
    public AjaxResult getBookValueUtilityEqualityRanking() {
        LoginUser loginUser = SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest());
        return AjaxResult.success(contractSponsorService.getBookValueUtilityEqualityRanking(loginUser.getUser().getDeptId()));
    }

    /**
     * 总收益
     */
    @ApiOperation(value = "总收益")
    @PostMapping("/getTotalEarnings")
    public AjaxResult getTotalEarnings() {
        LoginUser loginUser = SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest());
        return AjaxResult.success(contractSponsorService.getTotalEarnings(loginUser.getUser().getDeptId()));
    }

    /**
     * 逾期金额 + 逾期租客数量 + 收缴率 + 逾期率 + 逾期金额占比
     */
    @ApiOperation(value = "逾期金额 + 逾期租客数量 + 收缴率 + 逾期率 + 逾期金额占比")
    @PostMapping("/getRentCollection")
    public AjaxResult getRentCollection() {
        LoginUser loginUser = SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest());
        return AjaxResult.success(contractSponsorService.getRentCollection(loginUser.getUser().getDeptId()));
    }

    /**
     * 开票金额和减免金额
     */
    @ApiOperation(value = "开票金额和减免金额")
    @PostMapping("/getInvoiceAndCredit")
    public AjaxResult getInvoiceAndCredit() {
        LoginUser loginUser = SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest());
        return AjaxResult.success(contractSponsorService.getInvoiceAndCredit(loginUser.getUser().getDeptId()));
    }

    /**
     * 逾期租户比率
     */
    @ApiOperation(value = "逾期租户比率")
    @PostMapping("/getCountOverdueLesseeRate")
    public AjaxResult getCountOverdueLesseeRate() {
        LoginUser loginUser = SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest());
        return AjaxResult.success(contractSponsorService.getCountOverdueLesseeRate(loginUser.getUser().getDeptId()));
    }

    /**
     * 逾期率排名
     */
    @ApiOperation(value = "逾期率排名")
    @PostMapping("/getOverdueLesseeRateRanking")
    public AjaxResult getOverdueLesseeRateRanking() {
        LoginUser loginUser = SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest());
        return AjaxResult.success(contractSponsorService.getOverdueLesseeRateRanking(loginUser.getUser().getDeptId()));
    }

    /**
     * 逾期金额排名
     */
    @ApiOperation(value = "逾期金额排名")
    @PostMapping("/getOverdueLesseeAmountRanking")
    public AjaxResult getOverdueLesseeAmountRanking() {
        LoginUser loginUser = SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest());
        return AjaxResult.success(contractSponsorService.getOverdueLesseeAmountRanking(loginUser.getUser().getDeptId()));
    }

    /**
     * 租户总已缴租金排名
     */
    @ApiOperation(value = "租户总已缴租金排名")
    @PostMapping("/getCaptureLesseeAmountRanking")
    public AjaxResult getCaptureLesseeAmountRanking() {
        LoginUser loginUser = SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest());
        return AjaxResult.success(contractSponsorService.getCaptureLesseeAmountRanking(loginUser.getUser().getDeptId()));
    }

    /**
     * 总效益流失率
     */
    @ApiOperation(value = "总效益流失率")
    @PostMapping("/getTotalRateOfLossOfBenefits")
    public AjaxResult getTotalRateOfLossOfBenefits() {
        LoginUser loginUser = SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest());
        return AjaxResult.success(contractSponsorService.getTotalRateOfLossOfBenefits(loginUser.getUser().getDeptId()));
    }

    /**
     * 租金流失总额
     */
    @ApiOperation(value = "租金流失总额")
    @PostMapping("/getTotalRentLoss")
    public AjaxResult getTotalRentLoss() {
        LoginUser loginUser = SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest());
        return AjaxResult.success(contractSponsorService.getTotalRentLoss(loginUser.getUser().getDeptId()));
    }

    /**
     * 创建时间排前10的合同
     */
    @ApiOperation(value = "创建时间排前10的合同")
    @PostMapping("/getTop10ByCreateAt")
    public AjaxResult getTop10ByCreateAt() {
        LoginUser loginUser = SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest());
        return AjaxResult.success(contractSponsorService.getTop10ByCreateAt(loginUser.getUser().getDeptId()));
    }

    /**
     * 合同分类 + 出租类型
     */
    @ApiOperation(value = "合同分类 + 出租类型")
    @PostMapping("/getContractSponsorType")
    public AjaxResult getContractSponsorType() {
        LoginUser loginUser = SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest());
        return AjaxResult.success(contractSponsorService.getContractSponsorType(loginUser.getUser().getDeptId()));
    }

    /**
     * 租金收缴 近12个月：待付（应收）
     */
    @ApiOperation(value = "租金收缴 近12个月：待付（应收）")
    @PostMapping("/getContractSponsorReceivable")
    public AjaxResult getContractSponsorReceivable() {
        LoginUser loginUser = SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest());
        return AjaxResult.success(contractSponsorService.getContractSponsorReceivable(loginUser.getUser().getDeptId()));
    }

    /**
     * 租金收缴 近12个月：已收（实收）
     */
    @ApiOperation(value = "租金收缴 近12个月：已收（实收）")
    @PostMapping("/getContractSponsorReceipts")
    public AjaxResult getContractSponsorReceipts() {
        LoginUser loginUser = SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest());
        return AjaxResult.success(contractSponsorService.getContractSponsorReceipts(loginUser.getUser().getDeptId()));
    }

    /**
     * 租金收缴 近12个月：减免
     */
    @ApiOperation(value = "租金收缴 近12个月：减免")
    @PostMapping("/getContractSponsorCredit")
    public AjaxResult getContractSponsorCredit() {
        LoginUser loginUser = SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest());
        return AjaxResult.success(contractSponsorService.getContractSponsorCredit(loginUser.getUser().getDeptId()));
    }

    /**
     * 营业外收入与支出
     */
    @ApiOperation(value = "营业外收入与支出")
    @PostMapping("/getIncomingsAndOutgoings")
    public AjaxResult getIncomingsAndOutgoings() {
        LoginUser loginUser = SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest());
        return AjaxResult.success(contractSponsorService.getIncomingsAndOutgoings(loginUser.getUser().getDeptId()));
    }

    /**
     * 查询出租情况（出租面积+出租金额+出租率+收缴率）
     */
    @ApiOperation(value = "查询出租情况")
    @PostMapping("/getRentDetail")
    public Map<String, Object> getRentDetail() {
        LoginUser loginUser = SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest());
        return AjaxResult.success(contractSponsorService.getRentDetail(loginUser.getUser().getDeptId()));
    }

    @ApiOperation(value = "合同归档")
    @PostMapping("/pigeonhole")
    public AjaxResult pigeonhole(@RequestBody ContractSponsor contractSponsor){
        return toAjax(contractSponsorService.updateContractSponsorPigeonhole(contractSponsor));
    }


    /**
     *  续约
     */
    @ApiOperation(value = "续约")
    //@PreAuthorize("@ss.hasPermi('system:sponsor:edit')")
//    @Log(title = "续约", businessType = BusinessType.UPDATE)
    @PutMapping("/contractExtension")
    public AjaxResult contractExtension(@RequestBody ContractSponsor contractSponsor) throws ParseException {
        contractSponsor.setContractExtension("1");
        return toAjax(contractSponsorService.updateContractSponsor(contractSponsor));
    }


    @ApiOperation(value = "合同变更")
    @PostMapping("/alter")
    public AjaxResult alter(@RequestBody ContractSponsor contractSponsor) throws ParseException {
        return toAjax(contractSponsorService.alterContractSponsor(contractSponsor));
    }










    /**
     * 获取【合同发起】详细信息
     */
    @ApiOperation(value = "获取【合同发起】列详细信息")
    //@PreAuthorize("@ss.hasPermi('system:sponsor:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(contractSponsorService.selectContractSponsorById(id));
    }

    /**
     * 删除【合同发起】
     */
    @ApiOperation(value = "删除【合同发起】")
    //@PreAuthorize("@ss.hasPermi('system:sponsor:remove')")
//    @Log(title = "删除【合同发起】", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(contractSponsorService.deleteContractSponsorByIds(ids));
    }
    @Autowired
    private ContractBillMapper billMapper;
    /**
     * 查询【合同账单】列表
     */
    @ApiOperation(value = "查询【合同账单】列表")
    //@PreAuthorize("@ss.hasPermi('system:sponsor:list')")
    @GetMapping("/getBillList")
    public TableDataInfo getBillList(ContractBill contractBill) {
        LoginUser loginUser = SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest());
        contractBill.setDeptId(loginUser.getUser().getDeptId());
        startPage();
        List<ContractBill> list = billMapper.selectContractBillList(contractBill);
        return getDataTable(list);
    }


}
